package com.cgc.venus.server.job.jobdetail;
import com.cgc.venus.server.core.k8s.impl.K8sNodeServiceImpl;
import com.cgc.venus.server.core.k8s.inter.K8sNodeService;
import com.cgc.venus.server.core.utils.SpringUtil;
import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.job.Constants;
import io.fabric8.kubernetes.api.model.Node;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * 统计计算节点
 */
public class StatsNodeJob extends AbstractBaseJob {
    private static Logger logger = LoggerFactory.getLogger(StatsNodeJob.class);
    public StatsNodeJob() {
    }
    public void execute(JobExecutionContext context)  
        throws JobExecutionException {
        logger.info("统计计算节点job start...");
        List objs = new ArrayList<Object>();
        String sql="";
        String id="";
        try {
            //查询统计信息
            K8sNodeService k8sNodeService=SpringUtil.getBean(K8sNodeServiceImpl.class);
            List<Node> results=k8sNodeService.nodeDataQuery();
            int countAll=results.size();
            List<Node> resultsEx=results.stream().filter(ts -> "Unknown".equals(ts.getStatus().getConditions().get(3).getStatus())).collect(Collectors.toList());
            int countEx=resultsEx.size();
            SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");
            int countToday=results.stream().filter(ts -> dfs.format(new Date()).equals(ts.getMetadata().getCreationTimestamp().replace("T", " ").replace("Z", "").split(" ")[0])).collect(Collectors.toList()).size();
            //处理告警
            if(countEx>0){
                //往告警表插入一条记录
                String nodeExInfo="";
                for(Node node:resultsEx){
                    if(nodeExInfo.equals("")){
                        nodeExInfo+=node.getStatus().getAddresses().get(0).getAddress();
                    }else{
                        nodeExInfo+=","+node.getStatus().getAddresses().get(0).getAddress();
                    }
                }
                String alertMsg="平台计算节点"+countEx+"个有异常,异常节点ip:("+nodeExInfo+")";
                handleEx(alertMsg,Constants.ALARM_TYPE_NODE,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,Constants.ALARM_NS_ALL);
            }
            //更新统计值表
            sql="select id from t_job_stats_node where date_format(create_time,'%Y-%m-%d')=date_format(NOW(),'%Y-%m-%d')";
            List<Map<String, Object>> l=getJdbcTemplate().queryForList(sql);
            if(l!=null&&l.size()>0){
                //db update
                sql = "update t_job_stats_node  set node_count_all=?,node_count_ex=?,node_count_today=?,last_update_time=NOW() where id=?";
                id=l.get(0).get("id").toString();
            }else{
                //db insert
                sql = "INSERT INTO t_job_stats_node(node_count_all,node_count_ex,node_count_today,id,create_time,last_update_time) VALUES (?,?,?,?,NOW(),NOW())";
                id = StringUtil.getUUID();
            }
            objs.add(countAll);
            objs.add(countEx);
            objs.add(countToday);
            objs.add(id);
            getJdbcTemplate().update(sql, objs.toArray());
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            handleEx("统计计算节点任务异常,异常信息:"+getErrorInfoFromException(ex),Constants.ALARM_TYPE_JOB_ERROR,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,Constants.ALARM_NS_ALL);
            throw new JobExecutionException(ex);
        }
    }  
}